import pymysql
class DButils(object):
    conn = None
    # 先定义两个连接p2p数据库的私有方法,连接前和连接后的处理方式,然后执行SQL语句
    @classmethod
    def __get_conn(cls):
        # 是空则开启SQL
        if cls.conn is None:
            cls.conn = pymysql.Connect(host="user-p2p-test.itheima.net",port="3306",user="root",password="Itcast_p2p_20191228",database="czbk_member",charset="utf8")
            return cls.conn
    @classmethod
    # 不是空则关闭SQL
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
    @classmethod
    # 执行sql语句
    def select_sql(cls):
        cursor = None
        result = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute("sql")
            result = cursor.fetchall()
            # 查询所有fetchall,查询单个fetchone
        except Exception as e:
            print("查询时数据错误：{}".format(e))
        finally:
            cursor.close()
            cls.__close_conn()
            return result
    @classmethod
    def update_sql(cls,sql):
        cursor = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            cls.conn.commit()
        except Exception as e:
            print("更新时数据错误：{}".format(e))
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_conn()
